<template>
  <div>
    <div class="toolbox">
      <!-- <el-button @click="updateFirstRow">Update first row</el-button> -->
      <!-- <el-button @click="changeZoomLevel">Change zoom level</el-button> -->
      <el-form
        ref="ruleFormRef"
        :model="query"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
        inline
      >
        <el-form-item label="开始日期:" prop="start">
          <el-date-picker
            v-model="query.start"
            type="datetime"
            placeholder="选择开始日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="-" prop="end" label-width="10px">
          <el-date-picker
            v-model="query.end"
            type="datetime"
            placeholder="选择结束日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
          />
        </el-form-item>
        <el-form-item label="显示方式:" prop="size">
          <!-- <el-input
            type="number"
            v-model="query.size"
            max="22"
            min="1"
            @input="inputSize"
          ></el-input> -->
          <el-select v-model="query.size" placeholder="选择显示方式" @change="inputSize">
            <el-option label="月" :value="20" />
            <el-option label="日" :value="16" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button @click="newMachineNumber" type="success">新增机台号</el-button>
      <el-button @click="NewTask" type="success">新增任务</el-button>
    </div>
    <div class="gstc-wrapper" ref="gstcElement"></div>
    <el-dialog
      v-model="visibleModify"
      title="修改"
      width="25%"
      top="35vh"
      :before-close="
        () => {
          visibleModify = false
        }
      "
    >
      <el-form
        ref="ruleFormRef"
        :model="modalModify"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="机台号:" prop="title">
          <el-input v-model="modalModify.title" disabled="" />
        </el-form-item>
        <el-form-item label="名称:" prop="label">
          <el-input v-model="modalModify.label" />
        </el-form-item>
        <el-form-item label="开始日期:" prop="start">
          <el-date-picker
            v-model="modalModify.time.start"
            type="datetime"
            placeholder="选择开始日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 1000px"
          />
        </el-form-item>
        <el-form-item label="结束日期:" prop="end">
          <el-date-picker
            v-model="modalModify.time.end"
            type="datetime"
            placeholder="选择结束日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 1000px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleModify = false">取消</el-button>
          <el-button type="primary" @click="modify"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="visibleModifyNew"
      title="新增机台号"
      width="25%"
      top="35vh"
      :before-close="
        () => {
          visibleModifyNew = false
        }
      "
    >
      <el-form
        ref="ruleFormRef"
        :model="NewModel"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="机台号:" prop="title">
          <el-input v-model="NewModel.label" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleModifyNew = false">取消</el-button>
          <el-button type="primary" @click="modifyNew"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="visibleTask"
      title="新增任务"
      width="25%"
      top="35vh"
      :before-close="
        () => {
          visibleTask = false
        }
      "
    >
      <el-form
        ref="ruleFormRef3"
        :model="TaskModel"
        label-width="85px"
        class="demo-ruleForm"
        status-icon
        :rules="rules"
      >
        <el-form-item label="机台号:" prop="rowsId">
          <el-select
            v-model="TaskModel.rowsId"
            class="m-2"
            placeholder="选择机台号"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in rowsList"
              :key="index"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称:" prop="label" placeholder="请填写任务名称">
          <el-input v-model="TaskModel.label" />
        </el-form-item>
        <el-form-item label="开始日期:" prop="time.start">
          <el-date-picker
            v-model="TaskModel.time.start"
            type="datetime"
            placeholder="选择开始日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 1000px"
          />
        </el-form-item>
        <el-form-item label="结束日期:" prop="time.end">
          <el-date-picker
            v-model="TaskModel.time.end"
            type="datetime"
            placeholder="选择结束日期"
            format="YYYY-MM-DD HH:mm"
            value-format="x"
            style="width: 1000px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleTask = false">取消</el-button>
          <el-button type="primary" @click="modifyTask"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import GSTC from 'gantt-schedule-timeline-calendar/dist/gstc.wasm.esm.min.js'
import { Plugin as TimelinePointer } from 'gantt-schedule-timeline-calendar/dist/plugins/timeline-pointer.esm.min.js'
import { Plugin as Selection } from 'gantt-schedule-timeline-calendar/dist/plugins/selection.esm.min.js'
import { Plugin as ItemResizing } from 'gantt-schedule-timeline-calendar/dist/plugins/item-resizing.esm.min.js'
import { Plugin as ItemMovement } from 'gantt-schedule-timeline-calendar/dist/plugins/item-movement.esm.min.js'
import { Plugin as Bookmarks } from 'gantt-schedule-timeline-calendar/dist/plugins/time-bookmarks.esm.min.js'
import 'gantt-schedule-timeline-calendar/dist/style.css'
import { ref, onMounted, onBeforeUnmount, nextTick, reactive } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import locale from './ch-cn'
// helper functions
const ruleFormRef3 = ref()
const rules = reactive({
  label: [
    {
      required: true,
      message: '请填写任务名称',
      trigger: 'change',
    },
  ],
  rowsId: [
    {
      required: true,
      message: '请选择机台号',
      trigger: 'change',
    },
  ],
  time: {
    start: [
      {
        required: true,
        message: '选择开始日期',
        trigger: 'change',
      },
    ],
    end: [
      {
        required: true,
        message: '选择结束日期',
        trigger: 'change',
      },
    ],
  },
})
const generateRows = () => {
  /**
   * @type { import("gantt-schedule-timeline-calendar").Rows }
   */
  const rows = {}
  for (let i = 0; i < 100; i++) {
    const id = GSTC.api.GSTCID(i.toString())
    rows[id] = {
      id,
      label: `Row ${i}`,
    }
  }
  return rows
}

const generateItems = () => {
  /**
   * @type { import("gantt-schedule-timeline-calendar").Items }
   */
  const items = {}
  let start = GSTC.api.date().startOf('day').subtract(6, 'day')
  for (let i = 0; i < 100; i++) {
    const id = GSTC.api.GSTCID(i.toString())
    const rowId = GSTC.api.GSTCID(Math.floor(Math.random() * 100).toString())
    start = start.add(1, 'day')
    items[id] = {
      id,
      label: `Item ${i}`,
      rowId,
      time: {
        start: start.valueOf(),
        end: start.add(1, 'day').endOf('day').valueOf(),
      },
    }
  }
  return items
}

// main component

let gstc, state
const gstcElement = ref(null)
// 修改弹窗
const visibleModify = ref(false)
// 新增机台号弹窗
const visibleModifyNew = ref(false)
//  修改数据
const modalModify = ref({})
// 新增数据
const NewModel = ref({
  label: '',
})
// 查询数据
const query = ref({
  start: dayjs().startOf('month').valueOf(),
  end: dayjs().endOf('month').valueOf(),
  size: 16,
})
// 新增任务弹窗
const visibleTask = ref(false)
//新增任务
const TaskModel = ref({
  label: '',
  rowsId: '',
  time: {
    start: '',
    end: '',
  },
})
const months = [
  {
    zoomTo: 100, // we want to display this format for all zoom levels until 100
    period: 'month',
    periodIncrement: 10,
    format({ timeStart, vido }) {
      return vido.html`<div class="my-calendar-date" @click=${() =>
        onDateClick(timeStart)}>${timeStart.format('YYYY-MMMM')}</div>` // full list of formats: https://day.js.org/docs/en/display/format
    },
  },
]

const days = [
  {
    zoomTo: 100, // we want to display this format for all zoom levels until 100
    period: 'day',
    periodIncrement: 10,
    main: true, // we want grid to be divided by this period = day
    format({ timeStart, vido }) {
      // console.log(timeStart);
      return vido.html`<div class="my-calendar-date" @click=${() =>
        onDateClick(timeStart)}>${timeStart.format('MM-DD')}</div>` // full list of formats: https://day.js.org/docs/en/display/format
    },
  },
]
const setTippyContent = (element, data) => {
  if (!gstc) return
  if ((!data || !data.item) && element._tippy) return element._tippy.destroy()
  const itemData = gstc.api.getItemData(data.item.id)
  if (!itemData) return element._tippy.destroy()
  if (itemData.detached && element._tippy) return element._tippy.destroy()
  // @ts-ignore
  if (!itemData.detached && !element._tippy) tippy(element, { trigger: 'mouseenter click' })
  if (!element._tippy) return
  const { startDate, endDate } = itemData.time
  console.log(data)
  const tooltipContent = `
  <ul>
      <li>机台号：${data.row.label}</li>
      <li>开始日期：${startDate.format('YYYY-MM-DD HH:mm')}</li>
      <li> 开始时间：${endDate.format('YYYY-MM-DD HH:mm ')}</li>
    </ul> 
  `
  let bodyHtml = new DOMParser().parseFromString(tooltipContent, 'text/html').body
  bodyHtml.style.height = '100%'
  element._tippy.setContent(bodyHtml)
  // element._tippy.setContent(new DOMParser().parseFromString(tooltipContent, 'text/html').body)
}
const updateFirstRow = () => {
  state.update(`config.list.rows.${GSTC.api.GSTCID('0')}`, (row) => {
    row.label = 'Changed dynamically'
    return row
  })
  console.log(GSTC.api.GSTCID('0'))
}

const changeZoomLevel = () => {
  // state.update("config.chart.time.zoom", 21);
  config.value.list.rows['gstcid-7'] = {
    id: 'gstcid-7',
    label: '排产任务',
  }
  config.value.chart.items['gstcid-7'] = {
    id: 'gstcid-7',
    label: 'Item 7',
    rowId: 'gstcid-7',
    time: {
      start: dayjs('2023-4-8 1').valueOf(),
      end: dayjs('2023-4-8 24').valueOf(),
    },
  }
  nextTick(() => {
    console.log(config.value)
    state.update('config.list.rows', config.value.list.rows)
    state.update('config.chart.items', config.value.chart.items)
    console.log(state.data.$data)
  })
}
//缩放值更改事件
const inputSize = (val) => {
  console.log(val)
  state.update('config.chart.time.zoom', val)
}
//修改
const modify = () => {
  console.log()
  const { id, label, rowId, time } = modalModify.value
  nextTick(() => {
    state.update(`config.chart.items.${id}`, (row) => {
      row.label = label
      row.time = time
      return row
    })
    console.log(state.data.$data)
    visibleModify.value = false
  })
}
//新增保存
const modifyNew = () => {
  if (NewModel.value.label == '') {
    ElMessage({
      message: '请填写机台号',
      type: 'warning',
    })
    return
  }
  let Rows = gstc.api.getAllRows()
  let ItemsList = Object.values(Rows)
  let num = Number(ItemsList[ItemsList.length - 1].id.split('-')[1]) + 1
  Rows[`gstcid-${num}`] = {
    id: `gstcid-${num}`,
    label: NewModel.value.label,
  }
  state.update('config.list.rows', Rows)
  visibleModifyNew.value = false
}
//新增任务保存
const modifyTask = async () => {
  // state.data.origins.push("localhost:3000");
  console.log()
  await ruleFormRef3.value.validate((valid, fields) => {
    if (valid) {
      let Items = Object.values(gstc.api.getAllItems()).sort((a, b) => Number(a.id) - Number(b.id))
      let num = Number(Items[Items.length - 1].id) + 1
      let obj = gstc.api.getAllItems()
      obj[num] = {
        id: num,
        label: TaskModel.value.label,
        rowId: TaskModel.value.rowsId,
        time: TaskModel.value.time,
      }
      state.update('config.chart.items', obj)
      visibleTask.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 新增机台号按钮
const newMachineNumber = () => {
  NewModel.value.label = ''
  visibleModifyNew.value = true
}
const rowsList = ref([])
// 新增任务
const NewTask = () => {
  // TaskModel.value.rowsId = "";
  // TaskModel.value.label = "";
  // TaskModel.value.time.start = "";
  // TaskModel.value.time.end = "";
  if (ruleFormRef3.value) {
    ruleFormRef3.value.resetFields()
  }
  rowsList.value = Object.values(gstc.api.getAllRows())
  visibleTask.value = true
}
let canChangeRow = true
let canCollide = true
function isCollision(item) {
  const allItems = gstc.api.getAllItems()
  for (const itemId in allItems) {
    if (itemId === item.id) continue
    const currentItem = allItems[itemId]
    if (currentItem.rowId === item.rowId) {
      if (item.time.start >= currentItem.time.start && item.time.start <= currentItem.time.end)
        return true
      if (item.time.end >= currentItem.time.start && item.time.end <= currentItem.time.end)
        return true
      if (item.time.start <= currentItem.time.start && item.time.end >= currentItem.time.end)
        return true
      if (item.time.start >= currentItem.time.start && item.time.end <= currentItem.time.end)
        return true
    }
  }
  return false
}
const itemMovementOptions = {
  events: {
    onMove({ items }) {
      // console.log(items)
      return items.before.map((beforeMovementItem, index) => {
        if (beforeMovementItem.drag === false) {
          return items.initial[index]
        }
        const afterMovementItem = items.after[index]
        const myItem = GSTC.api.merge({}, afterMovementItem)
        if (!canChangeRow) {
          myItem.rowId = beforeMovementItem.rowId
        }
        // if (items.after[index].rowId !== items.initial[index].rowId) {
        //   let items1 = Object.values(gstc.api.getAllItems())
        //   let activeRow = items1.filter((item) => {
        //     return item.id != items.after[index].id && item.rowId == items.after[index].rowId
        //   })
        //   if (activeRow.length > 0) {
        //     let poniton = activeRow.some((cur) => {
        //       // debugger
        //       const { end, start } = items.after[index].time
        //       // console.log('cur.time.start---'+cur.time.start)
        //       // console.log('start---'+start)
        //       // console.log('end---'+end)
        //       console.log(cur.time.start)
        //       console.log(start)
        //       console.log(start >= cur.time.start)
        //       console.log(end >= cur.time.end)
        //       return start >= cur.time.start || end >= cur.time.end
        //     })
        //     // console.log(poniton)
        //     if (poniton) {
        //       return items.initial[index]
        //     }
        //   }
        // }
        if (!canCollide && isCollision(myItem)) {
          myItem.time = { ...beforeMovementItem.time }
          myItem.rowId = beforeMovementItem.rowId
        }
        return myItem
      })
    },
  },
  // snapToTime: {
  //   start({ startTime, time }) {
  //     // snap item start time to 12:00 AM while moving
  //     return startTime.startOf('day').add(12, 'hour')
  //   },
  // },
}
const itemResizingOptions = {
  events: {
    onStart({ items }) {
      return filterFrozenItems(items.after)
    },
    onResize({ items }) {
      return filterFrozenItems(items.after)
    },
    onEnd({ items }) {
      return filterFrozenItems(items.after)
    },
  },
  // snapToTime: {
  //   start({ startTime, time }) {
  //     conosle.log(items + 'onEnd')
  //     return startTime.startOf(time.period)
  //   },
  //   end({ endTime, time }) {
  //     conosle.log(items + 'onEnd')

  //     return endTime.endOf(time.period)
  //   },
  // },
}
const filterFrozenItems = (items) => {
  return items.filter((item) => {
    if (item.frozen) return false
    return true
  })
}
const config = ref({
  licenseKey:
    '====BEGIN LICENSE KEY====\nNGwFMwysmCjEb/gJPV9Sz7ByJ1DSSgM764fNuI6skXoqwqLYGvwRKe6SAPueWcU1rdByY5S+NkgIY99lRDeAGOYsofvgPDOFvi9W2YGOqL5TboK8q9yH9no8MTY+D0gOWpGruGZtn4bGsA952JE7BbGpGUr1dchkjg/NxZGT0uW95sCS9LLYMFOEHSdH3KNScVjcbpn3Nsqpkq5AqsIvdFlo1L2JwG1p4bdgPAwMAJ5elrR9yLoeaWzNBvEwJjMWWTulZ7m5akScCy1cFfSQOdJFq1IHhMj9eWVRZObQCPCKHxkLIoyit/8wIEkNWcC+GTNO002UYQgS6uJOaU/+Bg==||U2FsdGVkX1+OA3TdK/5t8j2dajv7UVl2+B4yjG5mTMBBbT7CwaIanTGnXKypeb+E5Ny4O5mlulvv4LghN4EOmef3q5wy/2YHYv6ZOUNqCgQ=\nG1W0652KwIAytTOJk6I/qCj90ACo+k1MWAi1E18Qjf5QfHPG8viXsKREasUEj/qt0TzUdrhHnl1HuAURl2QFkP3g3Imx31wgyu/hBUbqZREwo14r7k+7AFIIOS27qYBVng87hXYPrf/VQeqAs1vC7K/0oAc70aotzxtoXwgYq/6sqmWuYAYH5suEgsCFU6rjJ/TuV33GGclRviMz5PFhWWBUK7gsfvL5aPIK7VkJxehhPSBKBL80sPFjmGNofXhawkHfJU0FJD15EdVWnjioKNxpzDEWMp9HToE2bUpRnfLgY92vSpv9KrOySp2K3/f2ancD0DvWKjpbNonCMT7pJg==\n====END LICENSE KEY====',
  plugins: [
    TimelinePointer(),
    Selection(),
    ItemResizing(itemResizingOptions),
    ItemMovement(itemMovementOptions),
    Bookmarks(),
  ],
  height: 500,
  list: {
    columns: {
      data: {
        // [GSTC.api.GSTCID('id')]: {
        //   id: GSTC.api.GSTCID('id'),
        //   width: 60,
        //   data: ({ row }) => GSTC.api.sourceID(row.id),
        //   header: {
        //     content: '序号',
        //   },
        // },
        [GSTC.api.GSTCID('label')]: {
          id: GSTC.api.GSTCID('label'),
          width: 200,
          data: 'label',
          header: {
            content: '机台号',
          },
        },
      },
    },
    // rows: generateRows(),
    rows: {
      // 'gstcid-0': {
      //   id: 'gstcid-0',
      //   label: '排产任务0',
      // },
      // 'gstcid-1': {
      //   id: 'gstcid-1',
      //   label: '排产任务1',
      // },
      // 'gstcid-2': {
      //   id: 'gstcid-2',
      //   label: '排产任务2',
      // },
      // 'gstcid-4': {
      //   id: 'gstcid-4',
      //   label: '排产任务3',
      // },
      // 'gstcid-4': {
      //   id: 'gstcid-4',
      //   label: '排产任务4',
      // },
      // 'gstcid-5': {
      //   id: 'gstcid-5',
      //   label: '排产任务5',
      // },
      // 'gstcid-6': {
      //   id: 'gstcid-6',
      //   label: '排产任务6',
      // },
      // 'gstcid-7': {
      //   id: 'gstcid-7',
      //   label: '排产任务7',
      // },
    },
  },
  locale,
  chart: {
    // items: generateItems(),
    time: {
      from: query.value.start,
      to: query.value.end,
      zoom: query.value.size,
    },
    // calendarLevels: [months,days],
    items: {
      // 0: {
      //   id: '0',
      //   // name: "Item 0",
      //   label: 'Item 0',
      //   rowId: 'gstcid-0',
      //   time: {
      //     start: dayjs('2023-4-1 1').valueOf(),
      //     end: dayjs('2023-4-1 24').valueOf(),
      //   },
      //   style: { background: '#E74C3C' },
      //   drag: false, //是否可纵向拖拉
      //   frozen: true, //是否可横向拖拉
      //   // overlap:true
      //   // label: ({ item }) => {
      //   //   console.log(item);
      //   //   return `<div class="my-item">
      //   //     任务名称：${item.name}
      //   //     开始时间： ${dayjs(item.time.start).format("YYYY-MM-DD HH:mm")}
      //   //     结束时间： ${dayjs(item.time.end).format("YYYY-MM-DD HH:mm")}
      //   //   </div>`;
      //   // },
      //   // isHTML: true,
      // },
      // 1: {
      //   id: '1',
      //   label: 'Item 1',
      //   rowId: 'gstcid-1',
      //   time: {
      //     start: dayjs('2023-4-8 1').valueOf(),
      //     end: dayjs('2023-4-8 24').valueOf(),
      //   },
      //   style: { background: '#DA3C78' },
      // },
      // 2: {
      //   id: '2',
      //   label: 'Item 2',
      //   rowId: 'gstcid-2',
      //   time: {
      //     start: dayjs('2023-4-9 1').valueOf(),
      //     end: dayjs('2023-4-9 24').valueOf(),
      //   },
      //   style: { background: '#7E349D' },
      // },
      // 3: {
      //   id: '3',
      //   label: 'Item 3',
      //   rowId: 'gstcid-4',
      //   time: {
      //     start: dayjs('2023-4-10 1').valueOf(),
      //     end: dayjs('2023-4-10 24').valueOf(),
      //   },
      //   style: { background: '#0077C0' },
      // },
      // 4: {
      //   id: '4',
      //   label: 'Item 4',
      //   rowId: 'gstcid-4',
      //   time: {
      //     start: dayjs('2023-4-9 1').valueOf(),
      //     end: dayjs('2023-4-9 24').valueOf(),
      //   },
      //   style: { background: '#07ABA0' },
      // },
      // 5: {
      //   id: '5',
      //   label: 'Item 5',
      //   rowId: 'gstcid-5',
      //   time: {
      //     start: dayjs('2023-4-8 1').valueOf(),
      //     end: dayjs('2023-4-8 24').valueOf(),
      //   },
      //   style: { background: '#0EAC51' },
      // },
      // 6: {
      //   id: '6',
      //   label: 'Item 6',
      //   rowId: 'gstcid-6',
      //   time: {
      //     start: dayjs('2023-4-1 1').valueOf(),
      //     end: dayjs('2023-4-1 24').valueOf(),
      //   },
      //   style: { background: '#F1892D' },
      // },
      // 7: {
      //   id: '7',
      //   label: 'Item 7',
      //   rowId: 'gstcid-7',
      //   time: {
      //     start: dayjs('2023-4-1 1').valueOf(),
      //     end: dayjs('2023-4-1 24').valueOf(),
      //   },
      // },
      // 8: {
      //   id: '8',
      //   label: 'Item 7',
      //   rowId: 'gstcid-7',
      //   time: {
      //     start: dayjs('2023-4-8 1').valueOf(),
      //     end: dayjs('2023-4-8 24').valueOf(),
      //   },
      // },
    },
  },
  actions: {
    'chart-timeline-items-row-item': [
      (element, data) => {
        setTippyContent(element, data)
        const onClick = (e) => {
          e.preventDefault()
          // console.log(data)
          visibleModify.value = true
          modalModify.value = {
            label: data.item.label,
            time: data.item.time,
            title: data.row.label,
            rowId: data.row.id,
            id: data.item.id,
          }
          return false
        }
        element.addEventListener('contextmenu', onClick)
        return {
          update(element, newData) {
            data = newData
            setTippyContent(element, data)
          },
          destroy(element, data) {
            element.removeEventListener('click', onClick)
            if (element._tippy) element._tippy.destroy()
          },
        }
      },
    ], // 监听右击事件
    // "chart-timeline-items-row":[
    // (element, data) => {
    //   console.log(element)
    //   console.log(data)
    // }
    // ],
    // "main":[
    // (element, data) => {
    //   console.log(element)
    //   console.log(data)
    // }
    // ],
  },
})

onMounted(() => {
  /**
   * @type { import("gantt-schedule-timeline-calendar").Config }
   */

  state = GSTC.api.stateFromConfig(config.value)
  globalThis.state = state
  gstc = GSTC({
    element: gstcElement.value,
    state,
  })
  globalThis.gstc = gstc
  console.log(state)
  getList()
  // console.log(config.value);
})
const getList = () => {
  let arr = {
    code: 200,
    message: '成功',
    data: {
      2: {
        56: {
          area: '二楼',
          machineCode: '2',
          serialNum: 2,
          alreadyWeight: 700,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-20 11:54:10',
          greyName: '8S/1普梳T/C 65/35环锭纺+16S/2普梳 T/C65/35环锭纺+双卫衣',
          updateName: 'zpf1',
          greyCode: 'WY1010N0003',
          56: 56,
          weavDeliveryDate: '2023-03-31',
          createTime: '2023-03-20 11:54:10',
          pieceNum: 28,
          startTime: '2023-03-23 04:01:40',
          endTime: '2023-03-25 12:01:40',
          id: 56,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023032000008',
          weavingCode: '1AA012',
          createName: 'zpf1',
          productType: '',
          deleteState: 0,
        },
        69: {
          area: '二楼',
          machineCode: '2',
          serialNum: 5,
          alreadyWeight: 25,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-24 10:22:31',
          greyName:
            '8S/1普梳T/C 65/35环锭纺+16S/2普梳 T/C65/35环锭纺+21S/2普梳 CVC60/40环锭纺+双卫衣',
          updateName: 'lfy',
          greyCode: 'WWY1032N0001',
          weavDeliveryDate: '2023-03-30',
          69: 69,
          createTime: '2023-03-24 10:22:31',
          pieceNum: 1,
          startTime: '2023-03-29 21:01:40',
          endTime: '2023-03-29 23:01:40',
          id: 69,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023032300020',
          weavingCode: '1AA088',
          createName: 'lfy',
          productType: '',
          deleteState: 0,
        },
        285: {
          area: '二楼',
          machineCode: '2',
          serialNum: 7,
          alreadyWeight: 975,
          yarnLong: '',
          285: 285,
          productionState: 0,
          updateTime: '2023-04-01 15:15:31',
          greyName: '14S/1超柔棉 气流纺+150D/144F涤纶 DTY全消光+120D/72F涤纶 DTY半光+双珠地',
          updateName: 'zpf1',
          greyCode: 'SZ1010B0005',
          weavDeliveryDate: '2023-04-05',
          createTime: '2023-04-01 15:15:31',
          pieceNum: 39,
          startTime: '2023-04-01 17:15:30',
          endTime: '2023-04-04 23:15:30',
          id: 285,
          workDrum: "34''“22GG*1800T*120",
          maintainType: '',
          planOrderCode: 'J2023032900005',
          weavingCode: '1AA032',
          createName: 'zpf1',
          productType: '',
          deleteState: 0,
        },
        60: {
          area: '二楼',
          machineCode: '2',
          serialNum: 3,
          alreadyWeight: 500,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-20 19:02:35',
          greyName: '14S/1超柔棉 气流纺+150D/144F涤纶 DTY全消光+120D/72F涤纶 DTY半光+双珠地',
          updateName: 'liudehua',
          greyCode: 'SZ1010B0005',
          weavDeliveryDate: '2023-03-31',
          createTime: '2023-03-20 19:02:35',
          pieceNum: 20,
          60: 60,
          startTime: '2023-03-25 19:31:40',
          endTime: '2023-03-27 11:31:40',
          id: 60,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023032000024',
          weavingCode: '1AA073',
          createName: 'liudehua',
          productType: '',
          deleteState: 0,
        },
        50: {
          area: '二楼',
          machineCode: '2',
          serialNum: 1,
          alreadyWeight: 600,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-20 10:01:56',
          greyName: '8S/1普梳T/C 65/35环锭纺+16S/2普梳 T/C65/35环锭纺+40S棉花灰波比布',
          updateName: 'zpf1',
          greyCode: 'BQ5099E01P',
          weavDeliveryDate: '2023-03-31',
          createTime: '2023-03-20 10:01:56',
          pieceNum: 24,
          startTime: '2023-03-20 19:01:40',
          50: 50,
          endTime: '2023-03-22 19:01:40',
          id: 50,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023031800003',
          weavingCode: '1AA002',
          createName: 'zpf1',
          productType: '',
          deleteState: 0,
        },
        108: {
          area: '二楼',
          machineCode: '2',
          serialNum: 6,
          alreadyWeight: 200,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-25 15:03:39',
          greyName: '14S/1超柔棉 气流纺+150D/144F涤纶 DTY全消光+120D/72F涤纶 DTY半光+双珠地',
          updateName: 'zpf1',
          greyCode: 'SZ1010B0005',
          weavDeliveryDate: '2023-03-31',
          createTime: '2023-03-25 15:03:39',
          pieceNum: 8,
          startTime: '2023-03-30 06:31:40',
          endTime: '2023-03-30 23:31:40',
          id: 108,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023032500009',
          weavingCode: '1AA094',
          108: 108,
          createName: 'zpf1',
          productType: '',
          deleteState: 0,
        },
        65: {
          area: '二楼',
          machineCode: '2',
          serialNum: 4,
          alreadyWeight: 600,
          yarnLong: '',
          productionState: 0,
          updateTime: '2023-03-21 16:05:31',
          greyName: '14S/1超柔棉 气流纺+150D/144F涤纶 DTY全消光+120D/72F涤纶 DTY半光+双珠地',
          updateName: 'liudehua',
          greyCode: 'SZ1010B0005',
          weavDeliveryDate: '2023-03-31',
          createTime: '2023-03-21 16:05:31',
          pieceNum: 24,
          startTime: '2023-03-27 13:31:40',
          endTime: '2023-03-29 13:31:40',
          id: 65,
          workDrum: "34''“22GG*1800T*120",
          planOrderCode: 'J2023032100006',
          weavingCode: '1AA016',
          createName: 'liudehua',
          productType: '',
          65: 65,
          deleteState: 0,
        },
        327: {
          area: '二楼',
          machineCode: '2',
          serialNum: 8,
          alreadyWeight: 50,
          yarnLong: '',
          productionState: 3,
          updateTime: '2023-04-19 13:45:19',
          greyName:
            '070N/4精梳1 1 亚赛尓/C100% 0/80 低弹 汽流纺 +20D/4普梳 T 100 低弹 涡流纺+0123/48 亚麻类 100 硬纱 紧密纺+阿斯达',
          updateName: 'cc',
          greyCode: 'WQEWQ00022N0031',
          weavDeliveryDate: '2023-04-29',
          createTime: '2023-04-19 11:23:56',
          pieceNum: 2,
          startTime: '2023-04-19 20:15:39',
          endTime: '2023-04-28 23:15:39',
          id: 327,
          workDrum: "11''“11GG*111T*333",
          maintainType: '',
          planOrderCode: 'J2023041700001',
          weavingCode: '1AA005',
          createName: 'sjs',
          productType: '',
          deleteState: 0,
          327: 327,
        },
      },
    },
    timeStamp: '2023-04-20 10:38:25',
  }
  let rows = {}
  let items = {}
  for (let key in arr.data) {
    rows['gstcid-' + key] = {
      id: 'gstcid-' + key,
      label: key,
    }
    for (let key1 in arr.data[key]) {
      let { id, startTime, endTime } = arr.data[key][key1]
      items[id] = {
        id: id,
        // label: startTime + ' 至 ' + endTime,
        label: id,
        rowId: 'gstcid-' + key,
        time: {
          start: dayjs(startTime).valueOf(),
          end: dayjs(endTime).valueOf(),
        },
      }
    }
  }
  console.log(rows)
  console.log(items)
  state.update('config.list.rows', rows)
  state.update('config.chart.items', items)
}
onBeforeUnmount(() => {
  if (gstc) gstc.destroy()
})
</script>
<style scoped>
.toolbox {
  padding: 10px;
  background: #fff;
}
/* .gstc-component {
  margin: 0;
  padding: 0;
}
.toolbox {
  padding: 10px;
}
:deep(.gstc__list) {
  border: 1px solid #7b7b7b;
}
:deep(.gstc__list-column-row, .gstc__list-column-header) {
  border-right: 1px solid #7b7b7b;
  border-bottom: 1px solid #7b7b7b;
}
:deep(.gstc__list-column-header) {
  border-bottom: 1px solid #7b7b7b;
  border-right: 1px solid #7b7b7b;
}
:deep(.gstc__chart-calendar) {
  border-top: 1px solid #7b7b7b;
  border-bottom: 1px solid #7b7b7b;
  border-right: 1px solid #7b7b7b;
  border-left: 0px;
}
:deep(.gstc__chart-calendar-date--day) {
  border-right: 1px solid #7b7b7b;
}
:deep(.gstc__chart-calendar-date) {
  border-right: 1px solid #7b7b7b;
  border-top: 1px solid #7b7b7b;
}
 */
:deep(.gstc__chart-timeline-grid-row-cell) {
  border-right: 1px solid #d8d7d7;
  border-top: 1px solid #d8d7d7;
}
:deep(.tippy-box) {
  border: 1px solid #333;
  color: #000;
  background-color: #fff;
}
</style>
